package com.ruoyi.goods.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.goods.config.DelayedConfig;
import com.ruoyi.goods.domain.BmGoods;
import com.ruoyi.goods.domain.BmInorderlist;
import com.ruoyi.goods.domain.BmSpecification;
import com.ruoyi.goods.service.SellerService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author {那蓝桉}
 * @Date: 2023/07/28/ 9:11
 * @description
 */
@Component
public class OrderConsumer {
    @Autowired
    private SellerService sellerService;
    @Autowired
    private RedisService redisService;
//    监听，绑定队列和交换机
    @RabbitListener(bindings = {@QueueBinding(value = @Queue,exchange = @Exchange(type="direct",name = "XXX"),key = {"seckillGoods.downSheves"})})
    public void recive1(String message){
        BmInorderlist order = JSONObject.parseObject(message, BmInorderlist.class);
        System.out.println("接收到订单创建成功,订单的编号为"+order.getOrderCode()+"的订单已经创建成功");
    }
    @RabbitListener(queues = DelayedConfig.DELAYED_QUEUE_NAME)
    public void receive(Message message){
        String msg=new String(message.getBody());
        String key = "goodsList:queryAll";
        List<BmGoods> goods = redisService.getCacheObject(key);
        if(goods!=null) {
            for (int i = 0; i < goods.size(); i++) {
//            下架
                sellerService.updateStatus0(goods.get(i).getBmPreferentiallist().get(0).getId());
//         实现秒杀商品下架后，去更新数据库的库存
                BmSpecification bmSpecification = goods.get(i).getBmSpecificationList().get(0);
                Long id = bmSpecification.getId();
                Long stock = redisService.getCacheObject("list:" + id.toString());
                BmSpecification bmSpecification2 = new BmSpecification();
                bmSpecification2.setId(id);
                bmSpecification2.setStock(stock);
                int num = sellerService.decrStockCount(bmSpecification2);
                System.out.println("num = " + num);
            }
        }
        redisService.deleteObject(key);


        System.out.println("当前时间："+new Date()+",收到延迟队列的消息："+msg);
    }
}
